package com.hlg.xboot.web.controller;

import com.hlg.xboot.exceptions.ErrorCode;
import com.hlg.xboot.vo.RestBody;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>Description:替换springboot 默认的BasicErrorController重新定向错误页面</p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 *
 * @author gaol
 * @version 1.0
 * @date 2017/5/23
 */
@RestController
public class CustomErrorController extends BaseController implements ErrorController {

    private static Logger logger = LoggerFactory.getLogger(CustomErrorController.class);

    @Value("${error.path:/error}")
    private String errorPath;

    @Override
    public String getErrorPath() {
        return errorPath;
    }


    /**
     * 自定义返回信息
     * @param request
     * @return
     */
    @RequestMapping(value = "${error.path:/error}")
    public RestBody handleError(HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        Map<String, Object> attributes = getErrorAttributes(request);
        int code = ErrorCode.SERVER_SYSERR.getCode();
        String message = (String) attributes.get("message");
        if (StringUtils.isEmpty(message)) {
            message = (String) attributes.get("error");
        }
        logger.error("exception :{}--{}", code, message);
        return failure(code, message);
    }


    /**
     * 获取错误信息
     *
     * @param request
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        ErrorAttributes errorAttributes = new DefaultErrorAttributes();
        return errorAttributes.getErrorAttributes(requestAttributes, false);
    }


}
